<template>
  <div class="app-container">
    <div class="search-container">
      <div class="button-container">
        <el-button :disabled="true" type="danger"><el-icon>
            <Plus />
          </el-icon>&nbsp;新增</el-button>
        <el-button :disabled="false" type="danger" @click="submitForm(ruleFormRef)"><el-icon>
            <Plus />
          </el-icon>&nbsp;保存</el-button>
        <el-button :disabled="false" type="danger"><el-icon>
            <Plus />
          </el-icon>&nbsp;撤销</el-button>
        <el-button :disabled="true" type="danger"><el-icon>
            <Plus />
          </el-icon>&nbsp;删除</el-button>
      </div>
      <el-form ref="dataFormRef" style="max-width: 100%" :model="form" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <el-row :gutter="20">
          <el-col :span="8" :offset="0">
            <el-form-item label="采购员" prop="buyer">
              <el-select v-model="form.buyer" placeholder="请选择采购员" clearable style="width: 250px">
                <el-option label="刘永刚" value="刘永刚" />
                <el-option label="孟盘龙" value="孟盘龙" />
                <el-option label="赵秋实" value="赵秋实" />
                <el-option label="牛骞若" value="牛骞若" />
                <el-option label="赵思彤" value="赵思彤" />
                <el-option label="于晋哲" value="于晋哲" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="采购日期" prop="dateOfPurchase">
              <el-date-picker v-model="form.dateOfPurchase" type="date" placeholder="请选择采购日期" clearable
                :value-format="'YYYY-MM-DD HH:mm:ss'" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="羊只类型" prop="sheepType">
              <el-select v-model="form.sheepType" placeholder="请选择羊只类型" clearable style="width: 250px">
                <el-option label="种公" :value="1" />
                <el-option label="种母" :value="2" />
                <el-option label="后裔" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">

          <el-col :span="8" :offset="0">
            <el-form-item label="供应商" prop="vendorSnowId">
              <el-select v-model="form.vendorSnowId" placeholder="请选择供应商" clearable style="width: 250px">
                <el-option v-for="item in tableDatas" :label="item.vendorName" :value="item.vendorSnowId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="仓库" prop="warehouse">
              <el-select v-model="form.warehouse" placeholder="请选择仓库" clearable style="width: 250px">
                <el-option v-for="item in originList" :label="item.sheepFullName" :value="item.sheepFullName" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8" :offset="0">
            <el-form-item label="摘要" prop="summaryEnum">
              <el-select v-model="form.summaryEnum" placeholder="请选择摘要" clearable style="width: 250px">
                <el-option :label="item.name" :value="item.value" v-for="item in summaryEnumList" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="单据号"> — — </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="流水号"> — — </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
  <div class="select">
    <el-table :data="tableDate" stripe style="width: 100%;height: 500px;">
      <el-table-column prop="earTag" label="批次/耳号" width="140">
        <template #default="scope">
          <el-select v-model="scope.row.earTag" placeholder="请选择耳号">
            <el-option :label="item.earTagNumber" :value="item.earTagNumber" v-for="item in erars" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="buildingId" label="栋舍Id" width="140">
        <template #default="scope">
          <el-select v-model="scope.row.buildingId" placeholder="请选择栋舍ID"
            @change="getcolumnIdList(scope.row.buildingId)">
            <el-option :label="item.ridgepoleName" :value="item.ridgepoleId" v-for="item in buildingIdList" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="columnId" label="栏位Id" width="140">
        <template #default="scope">
          <el-select v-model="scope.row.columnId" placeholder="请选择栋舍ID">
            <el-option :label="item.columnName" :value="item.columnManagementId" v-for="item in columnIdList" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="gender" label="性别" width="140">
        <template #default="scope">
          <el-select v-model="scope.row.gender" placeholder="请选择性别">
            <el-option label="公" :value="true" />
            <el-option label="母" :value="false" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="variety" label="品种" width="140">
        <template #default="scope">
          <el-select v-model="scope.row.variety" placeholder="请选择品种">
            <el-option v-for="item in sheepTypes" :label="item.name" :value="item.value" />

          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="goodName" label="商品名称" width="140">
        <template #default="scope" prop="goodName">
          <el-input v-model="scope.row.goodName" placeholder="请输入商品名称" />
        </template>
      </el-table-column>
      <el-table-column prop="labelPackage" label="标包" width="140">
        <template #default="scope">
          <el-input v-model="scope.row.labelPackage" placeholder="请输入标包" />
        </template>
      </el-table-column>
      <el-table-column prop="unitOfMeasure" label="计量单位" width="140">
        <template #default="scope">
          <el-input v-model="scope.row.unitOfMeasure" placeholder="请输入计量单位" />
        </template>
      </el-table-column>
      <el-table-column prop="inboundQuantity" label="入库数量" width="140">
        <template #default="scope">
          <el-input v-model="scope.row.inboundQuantity" placeholder="请输入入库数量" @input="calculateAmount(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="averageUnitOnly" label="只均单价（元）" width="140">
        <template #default="scope">
          <el-input v-model="scope.row.averageUnitOnly" placeholder="请输入只均单价（元）" @input="calculateAmount(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="amount" label="金额（元）" width="200">
        <template #default="scope">
          <el-input v-model="scope.row.amount" placeholder="请输入金额（元）" @input="overMoney(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="unitDiscounts" label="单位折扣（元）" width="200">
        <template #default="scope">
          <el-input v-model="scope.row.unitDiscounts" placeholder="请输入单位折扣（元）" @input="overMoney(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="adjustTheAmount" label="调整金额（元）" width="200">
        <template #default="scope">
          <el-input v-model="scope.row.adjustTheAmount" placeholder="请输入调整金额（元）" @input="overMoney(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="settlementAmount" label="结算金额（元）" width="200">
        <template #default="scope">
          <el-input v-model="scope.row.settlementAmount" placeholder="请输入结算金额（元）" />
        </template>
      </el-table-column>
      <el-table-column prop="totalWeight" label="总重量（公斤）" width="200">
        <template #default="scope">
          <el-input v-model="scope.row.totalWeight" placeholder="请输入总重量（公斤）" />
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="count">
    <span style="float: left"> 合计 </span>
    <span style="float: right"> 0.00 </span>
  </div>
  <div class="count1">
    <el-button link type="danger" @click="Addform()"> + 增行 </el-button>
    <el-button link type="danger" @click="Deleteform()"> - 删行 </el-button>
  </div>
  <div class="count2">
    <el-form ref="ruleFormRef" :model="form" label-width="auto" class="demo-ruleForm" status-icon>
      <el-form-item label="备注">
        <el-input v-model="form.purchaseFormDesc" type="textarea" placeholder="请输入备注信息" />
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import purcure from '@/api/PurchaseMent/index'
import { purcoreQuery, buildingIdQuery } from '@/api/PurchaseMent/model'
import vendor from '@/api/VendorMangMent/index'
import { vendorQuery } from '@/api/VendorMangMent/model'
import { startQuert } from "@/api/EarTagManagement/model";
import orign, { organQuery } from '@/api/OrganizationalAdministration/index'
const form = reactive({
  "buyer": "",//采购员
  "dateOfPurchase": "2024-07-29 00:00:00",//采购日期
  "sheepType": "",//羊只类型
  "vendorSnowId": "",//供应商
  "warehouse": "",//仓库（羊场总仓库）
  "summaryEnum": "",//摘要
  "purchaseFormDesc": "",//备注
})
//参数
const tableDate = reactive([
  {
    "buyer": "",//采购员
    "dateOfPurchase": "2024-07-29 00:00:00",//采购日期
    "sheepType": "",//羊只类型
    "vendorSnowId": "",//供应商
    "warehouse": "",//仓库（羊场总仓库）
    "summaryEnum": "",//摘要
    "purchaseFormDesc": "",//备注
    "document": "",//单据号
    "serialNumber": "",//流水号
    "earTag": "",// 批次/耳号（可视耳号）
    "buildingId": "",//栋舍Id
    "buildingName": "",//栋舍名称
    "columnId": "",//转入栏位Id
    "columnName": "",//转入栏位名称
    "gender": null,//公母（true公 false 母）
    "goodName": "",//商品名称
    "labelPackage": "",//标包
    "unitOfMeasure": "",//计量单位
    "inboundQuantity": null,//入库数量
    "averageUnitOnly": null,//只均单元（元）
    "amount": null,//金额
    "unitDiscounts": null,//单位折扣（元）
    "adjustTheAmount": null,//调整金额（元）
    "settlementAmount": null,//结算金额（元）
    "totalWeight": null,//总重量（公斤）


    "createBy": "",//创建人
    "createTime": "2024-07-29 00:00:00",// 创建时间（采购日期）
    "updateBy": "",//修改人
    "updateTime": "2024-07-29 00:00:00",//修改时间
    "isDel": false,//是否删除
    "variety": ""//品种
  }
])
onMounted(() => {
  getVendorList()
  getSummaryEnum()
  getBuildingIdList()
  getcolumnIdList()
  getSheepNos()
  getSheepType()
  getOriginList()
})
//计算总额
const calculateAmount = (row: any) => {
  row.amount = row.inboundQuantity * row.averageUnitOnly;
}
//计算结算金额
const overMoney = (row: any) => {
  row.settlementAmount = row.settlementAmount = row.amount - (row.unitDiscounts * row.inboundQuantity) - row.adjustTheAmount;
}
const c = ref(0);
//增行
const Addform = () => {
  c.value = 1;
  tableDate.forEach((item) => {
    c.value++;
  });
  tableDate.push({
    "document": "",//单据号
    "serialNumber": "",//流水号
    "earTag": "",// 批次/耳号（可视耳号）
    "buildingId": null,//栋舍Id
    "buildingName": "",//栋舍名称
    "columnId": null,//转入栏位Id
    "columnName": "",//转入栏位名称
    "gender": null,//公母（true公 false 母）
    "goodName": "",//商品名称
    "labelPackage": "",//标包
    "unitOfMeasure": "",//计量单位
    "inboundQuantity": null,//入库数量
    "averageUnitOnly": null,//只均单元（元）
    "amount": null,//金额
    "unitDiscounts": null,//单位折扣（元）
    "adjustTheAmount": null,//调整金额（元）
    "settlementAmount": null,//结算金额（元）
    "totalWeight": null,//总重量（公斤）
    "createBy": "",//创建人
    "createTime": "2024-07-29 00:00:00",// 创建时间（采购日期）
    "updateBy": "",//修改人
    "updateTime": "2024-07-29 00:00:00",//修改时间
    "isDel": false,//是否删除
    "variety": ""//品种
  })
  localStorage.setItem("data", JSON.stringify(tableDate));
}
//删行
const Deleteform = () => {
  tableDate.pop();
  localStorage.setItem("data", JSON.stringify(tableDate));
};
///供应商
//参数
const formInlines = reactive<vendorQuery>({
  venDorCode: "",
  vendorName: "",
  responsiblePhone: "",
  markets: "",
  salesman: "",
  useState: true,
  pageIndex: 1,
  pageSize: 100
})
//数据显示
//总条数
const totalCounts = ref()
const pageCounts = ref()
const tableDatas: any = ref([])
const getVendorList = () => {
  vendor.getList(formInlines).then((res: any) => {
    console.log('完整响应数据:', res);
    tableDatas.value = res.data.data
    totalCounts.value = res.data.totalCount
    pageCounts.value = res.data.pageCount
  })
}
//摘要
const summaryEnumList = ref([])
const getSummaryEnum = () => {
  purcure.getAbstract().then((res: any) => {
    summaryEnumList.value = res.data
  })
}
//获取栋舍
const forms = reactive<buildingIdQuery>({
  "pageIndex": 1,
  "pageSize": 100,
  "ridgepoleTypeId": 0,
  "ridgepoleName": "",
  "responsiblePerson": ""
})
const buildingIdList: any = ref([])
const getBuildingIdList = () => {
  purcure.getrid(forms).then((res: any) => {
    buildingIdList.value = res.data.data
  })
}
//获取栏位
const columnIdList: any = ref([])
const getcolumnIdList = (id: any) => {
  console.log(id)
  purcure.getcolumn(id).then((res: any) => {
    columnIdList.value = res.data
    console.log(columnIdList.value)
  })
  columnIdList.value = []
}
//表单
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
//校验
const rules = reactive({
  buyer: [
    {
      required: true,
      message: "请选择采购员",
      trigger: "change",
    },
  ],
  dateOfPurchase: [
    {
      type: "date",
      required: true,
      message: "请选择采购日期",
      trigger: "change",
    },
  ],
  sheepType: [
    {
      required: true,
      message: "请选择羊只类型",
      trigger: "change",
    },
  ],
  goodName: [
    {
      required: true,
      message: "请选择羊只类型",
      trigger: "change",
    },
  ],
  unitOfMeasure: [
    {
      required: true,
      message: "请选择计量单位",
      trigger: "change",
    },
  ],
  vendorSnowId: [
    {
      required: true,
      message: "请选择供应商",
      trigger: "change",
    },
  ],
  warehouse: [
    {
      required: true,
      message: "请选择仓库",
      trigger: "change",
    },
  ],
  summaryEnum: [
    {
      required: true,
      message: "请选择摘要",
      trigger: "change",
    },
  ],
});
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      tableDate.forEach(c => {
        c.buyer = form.buyer
        c.dateOfPurchase = form.dateOfPurchase
        c.sheepType = form.sheepType
        c.purchaseFormDesc = form.purchaseFormDesc
        c.vendorSnowId = form.vendorSnowId
        c.warehouse = form.warehouse
        c.summaryEnum = form.summaryEnum
      })
      console.log(tableDate)
      purcure.addrid(tableDate).then(res => {
        ElMessage.success('添加成功')
        c.value = res
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
onMounted(() => {

})
//获取品种
const sheepTypes = ref([])
const getSheepType = () => {
  purcure.getbreed().then(res => {
    sheepTypes.value = res.data
  })
}
//耳号
const erars = ref([])
const getSheepNos = () => {
  purcure.getNoUseSheepNo().then(res => {
    erars.value = res.data
  })
}
//羊场
const origin = reactive<organQuery>({
  pageIndex: 1,
  pageSize: 100,
  sheepId: 0,
  sheepFullName: "",
  responsiblePerson: "",
})
const originList: any = ref([])
const getOriginList = () => {
  orign.getSheepFacroryList(origin).then((res: any) => {
    originList.value = res.data.data
  })
}
</script>
<style scoped>
.button-container {
  width: 100%;
  height: 40px;
}

.sel {
  width: 100%;
  height: 40px;
}

.select {
  margin-left: 1%;
  width: 98%;
  background-color: #fff;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  margin-top: -15px;
}

.count {
  width: 100%;
  height: 40px;
  font-weight: bold;
  border-bottom: 2px solid #f4f5f8;
  border-left: 2px solid #f4f5f8;
  border-right: 2px solid #f4f5f8;
  padding: 10px;
}

.count1 {
  width: 100%;
  height: 40px;
  border-bottom: 2px solid #f4f5f8;
  border-left: 2px solid #f4f5f8;
  border-right: 2px solid #f4f5f8;
  padding: 10px;
}

.count2 {
  width: 100%;
  height: 53px;
  border-bottom: 2px solid #f4f5f8;
  border-left: 2px solid #f4f5f8;
  border-right: 2px solid #f4f5f8;
  padding-bottom: 10px;
  padding-left: 10px;
}
</style>